<template>
  <div>
    <van-nav-bar
      title="我的地址列表"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
      :right-text="editing ? '完成' : '编辑'"
      @click-right="editing = !editing"
    />
    <van-address-list
      v-model="chosenAddressId"
      :list="list"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      @select="click"
      :add-button-text="editing ? '删除' : '新增地址'"
    />
  </div>
</template>

<script>
import { get, post } from "@/request/index";
export default {
  data() {
    return {
      chosenAddressId: 0,
      list: [],
      // 默认不编辑
      editing: false,
      // 要删除的地址
      delId: [],
      // 选择的地址
      index: 0,
    };
  },
  created() {
    this.getAddress();
  },
  methods: {
    // 请求
    getAddress() {
      get("/address/all")
        .then((res) => {
          let arr = res.list;
          let newarr = arr.map((item, index) => {
            return {
              ...item,
              id: item.addressId,
              address:
                item.country +
                item.province +
                item.city +
                item.county +
                item.addressDetail,
            };
          });

          console.log("地址", newarr);
          this.list = newarr;
        })
        .catch((err) => console.log(err));
    },
    onAdd() {
      if (this.editing) {
        // 删除操作
        post("/address/del", { addressId: this.delId })
          .then((res) => {
            console.log("成功删除");
            // 从列表中删去
            this.list.splice(this.index, 1);
          })
          .catch((err) => console.log("删除失败"));
      } else {
        //跳转添加页面
        this.$router.push("/address/add");
      }
    },
    onEdit(item, index) {
      console.log(item);
      this.$router.push({
        path: "/address/edit",
        query: item,
      });
    },
    click(item, index) {
      console.log("选中的地址", item);
      console.log("选择的id", index);
      if (this.editing) {
        // 选中地址操作
        this.delId = item.addressId;
        this.index = index;
      } else {
        // 选择地址并返回订单操作
        this.$router.push({
          path: "/order/preOrder",
          query: {
            ...item,
            preOrderId: this.$route.query.preOrderId,
          },
        });
      }
    },
  },
};
</script>

<style>
</style>